package org.msss.gamebasic;

import org.msss.resource.*;
import org.lwjgl.input.Keyboard;
import java.util.ArrayList;

/**
 * This class will hold the values of the view, gamemap, sprites, all that fun
 * stuff.
 * 
 * @author alanxoc3
 * 
 */
public final class Game {

	public static Room room;
	public static View view;

	private static ArrayList<Integer> keysDown;

	static {
		room = RoomDB.testRoom;
		view = new View();

		keysDown = new ArrayList<Integer>();
	}

	/**
	 * The game loop, this executes everything needed for the game from
	 * collecting input, to drawing.
	 */
	public static void loop() {
		timer();
		input();
		move();
		collision();
		draw();
		drawSprites();
	}

	/**
	 * Executes all of the timer events in the room.
	 */
	public static void timer() {
		// For all the sprites in the room, execute the timer method.
		for (Sprite loopSprite : room.getSprites()) {
			loopSprite.timer();
		}

		// For all the icons in the room, execute the timer method.
		for (Icon loopIcon : room.getIcons()) {
			loopIcon.timer();
		}
	}

	/**
	 * Executes all of the input events in the room. A key can be pressed,
	 * released, or down. Note: If a key is pressed, it is also down.
	 */
	public static void input() {

		// For all the sprites in the room, call the pressed, release, and down
		// methods. Based on what key has been pressed.

		while (Keyboard.next()) {
			if (Keyboard.getEventKeyState()) {
				keysDown.add(Keyboard.getEventKey());
			} else {
				keysDown.remove((Integer) Keyboard.getEventKey());
			}

			for (Sprite loopSprite : room.getSprites()) {
				if (Keyboard.getEventKeyState()) {
					// Pressed.
					loopSprite.pressed(Keyboard.getEventKey());
				} else {
					// Released.
					loopSprite.released(Keyboard.getEventKey());
				}
			}
		}

		// Down
		for (Sprite loopSprite : room.getSprites()) {
			for (int downLoop = 0; downLoop < keysDown.size(); downLoop++) {
				loopSprite.down(keysDown.get(downLoop));
			}
		}
	}

	/**
	 * Executes all of the move events in the room.
	 */
	public static void move() {
		for (Sprite spriteLoop : room.getSprites()) {
			spriteLoop.move();
		}
	}

	/**
	 * Executes all of the collision events in the room.
	 */
	public static void collision() {
		for (Sprite spriteLoop : room.getSprites()) {
			spriteLoop.collision();
		}
	}

	/**
	 * Executes all of the draw events in the room.
	 */
	public static void draw() {
		for (Sprite spriteLoop : room.getSprites()) {
			spriteLoop.draw();
		}
	}

	/**
	 * Draws the pictures of all the icons and sprites in the room. If a sprite
	 * is not visible, it will not draw it.
	 */
	public static void drawSprites() {
		// Icons
		for (Icon iconLoop : room.getIcons()) {
			Canvas.drawIcon(iconLoop);
		}

		// Sprites
		for (Sprite spriteLoop : room.getSprites()) {
			Canvas.drawSprite(spriteLoop);
		}
	}
}
